package com.tb.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @description: 工具类
 * @author: wangguichun
 * @create: 2018-04-13 21:54
 **/

public class MyUtils {

    /**
     * 产生 介于start~end之间的随机数
     *
     * @param start 起始范围
     * @param end   结束范围
     * @return int
     */
    public static int random(int start, int end) {
        return start + (int) (Math.random() * (end - start + 1));
    }

    /**
     * 根据request和cookie名取cookie
     *
     * @param request 页面请求
     * @param name    cookie名
     * @return cookie
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return null;
        if (cookies.length == 0) return null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                if (cookie.getValue().equals("")) return null;
                return cookie;
            }
        }
        return null;
    }


    /**
     * 过滤非法词汇
     *
     * @param target            待过滤的字符串
     * @param sensitiveWordList 违禁词汇列表
     * @return 处理后的字符串
     */
    public static String purifyString(String target, List<String> sensitiveWordList) {
        for (String s : sensitiveWordList) {
            if (target.contains(s)) {
                target = target.replace(s, "****");
            }
        }
        return target;
    }

}
